<template>
  <div class="register-wrap">
    <el-form
      class="register-container"
      :rules="rules"
      ref="registerForm"
      :model="registerForm"
      label-width="100px"
    >
      <h1 class="title">用户注册</h1>
      <el-form-item label="登录账号：" prop="username">
        <el-input
          type="text"
          v-model="registerForm.username"
          placeholder="登录账号"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="登录邮箱：" prop="email">
        <el-input
          type="text"
          v-model="registerForm.email"
          placeholder="登录邮箱"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="登录密码：" prop="password">
        <el-input
          type="password"
          v-model="registerForm.password"
          placeholder="登录密码"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码：" prop="confirmPassword">
        <el-input
          type="password"
          v-model="registerForm.confirmPassword"
          placeholder="请再次输入密码"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="验证码：" prop="captchaCode">
        <div class="code">
          <el-input
            type="text"
            auto-complete="false"
            v-model="registerForm.captchaCode"
            placeholder="点击图片更换验证码"
            style="width: 250px; margin-right: 1px"
          >
          </el-input>
          <img :src="captchas || defaultCaptcha" @click="getCaptcha()" />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="doSubmit()" style="width: 100%"
          >注册</el-button
        >
      </el-form-item>
      <el-row style="text-align: center; margin-top: -10px; margin-left: -50%">
        <i style="font-size: 12px; margin-right: 5px">已有账号?</i>
        <el-link type="primary" @click="gotoLogin()" :underline="false"
          >点此登录</el-link
        >
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { reqGetCode, reqUserRegister, reqCheckEmail } from "@/api";
export default {
  name: "Register",
  data() {
    // 验证密码复杂度（必须包含大小写字母）
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入密码"));
      }
      if (value.length < 6) {
        return callback(new Error("密码长度至少为6位"));
      }
      if (!/[a-z]/.test(value) || !/[A-Z]/.test(value)) {
        return callback(new Error("密码必须包含大小写字母"));
      }
      callback();
    };

    // 验证邮箱是否已注册
    const validateEmail = async (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入邮箱"));
      }
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
        return callback(new Error("请输入有效的邮箱地址"));
      }
      
      try {
        const res = await reqCheckEmail(value);
        if (res.code === 200 && res.data.exists) {
          callback(new Error("该邮箱已被注册"));
        } else {
          callback();
        }
      } catch (error) {
        console.error("邮箱验证失败:", error);
        callback();
      }
    };

    return {
      defaultCaptcha: require("@/assets/captcha.png"),
      captchas: "",
      registerForm: {
        username: "",
        password: "",
        confirmPassword: "",
        email: "",
        captchaCode: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入登录账号", trigger: "blur" },
          {
            min: 2,
            max: 14,
            message: "长度在 2 到 14 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, validator: validatePassword, trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, message: "请确认密码", trigger: "blur" },
          { validator: this.validateConfirmPassword, trigger: "blur" },
        ],
        // idType: [
        //   { required: true, message: "请选择证件类型", trigger: "blur" },
        // ],
        // idNumber: [
        //   { required: true, message: "请输入证件号码", trigger: "blur" },
        //   {
        //     min: 8,
        //     max: 18,
        //     message: "证件号码长度应在8到18位之间",
        //     trigger: "blur",
        //   }, // 假设身份证或其他证件号码长度在此范围内
        // ],
        email: [
          { required: true, validator: validateEmail, trigger: "blur" }
        ],
        captchaCode: [
          { required: true, message: "请输入验证码", trigger: "blur" }
        ],
      },
    };
  },
  methods: {
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.registerForm.password) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    },
    async doSubmit() {
      this.$refs.registerForm.validate(async (valid) => {
        if (valid) {
          try {
            const res = await reqUserRegister(this.registerForm);
            if (res.code === 200) {
              this.$message.success("注册成功");
              this.$router.push("/");
            } else {
              this.$message.error(res.message || "注册失败");
              await this.getCaptcha();
            }
          } catch (error) {
            console.error("注册失败:", error);
            this.$message.error("注册请求失败，请稍后重试");
            await this.getCaptcha();
          }
        } else {
          this.$message.error("注册信息有误，请检查后重新输入");
          return false;
        }
      });
    },
    gotoLogin() {
      this.$router.push("/");
    },
    async getCaptcha() {
      try {
        const res = await reqGetCode();
        if (res.code === 200) {
          this.captchas = res.data.captchaImage;
        } else {
          this.$message.error(res.message || "验证码获取失败");
        }
      } catch (error) {
        console.error("获取验证码失败:", error);
        this.$message.error("验证码获取失败");
      }
    },
  },
  mounted() {
    this.getCaptcha();
  },
};
</script>

<style scoped lang="scss">
/* 页面主体样式 */
.register-wrap {
  width: 100vw; /* 视窗宽度的100% */
  height: 100vh; /* 视窗高度的100% */
  background-image: url("@/assets/background4.jpg");
  background-size: 100%; /* 背景图片大小 */
  overflow: hidden; /* 隐藏溢出内容 */
}
.register-container {
  border-radius: 10px; /* 圆角边框 */
  // background-clip: padding-box; /* 背景剪裁至内边距框 */
  text-align: left; /* 文本左对齐 */
  padding-top: 10%;
  margin: 0 auto; /* 上下左右居中 */
  margin-top: 180px; /* 容器顶部外边距 */
  width: 380px; /* 固定宽度 */
  padding: 30px 35px 15px 35px; /* 内边距 */
  background: aliceblue; /* 背景颜色 */
  border: 1px solid #eaeaea; /* 边框 */
  box-shadow: 0 0 20px 2px rgba(0, 0, 0, 0.1); /* 阴影效果 */
  .title {
    margin: 0px auto 40px auto;
    text-align: center;
    color: #505458;
  }
  // 验证码样式
  .code {
    display: flex;
    flex-wrap: nowrap;
    img {
      width: 150px;
      height: 40px;
    }
  }
}
</style>
